<template>
  <div class="app-container">
    <div class="printer-designer-op">
      <div class="mr-4 text-xl font-bold">
        {{ templateObj.name ? `「${templateObj.name}」` : '' }}
      </div>
      <el-radio-group v-model="curPaper" @change="handlePaperChange">
        <el-radio-button
          v-for="item in paperTypes"
          :key="item.type"
          :value="item.type"
          :label="item.type"
        />
      </el-radio-group>
      <el-button icon="ZoomOut" class="ml-4" @click="changeScale(false)"> 缩小</el-button>
      <div class="mx-2">{{ (scaleValue * 100).toFixed(0) }}%</div>
      <el-button icon="ZoomIn" @click="changeScale(true)"> 放大</el-button>
      <el-button @click="rotatePaper">旋转纸张</el-button>
      <el-button @click="clearPaper">清空纸张</el-button>
      <el-button @click="exportJson">导出模版</el-button>
      <div class="flex-1"></div>
      <el-button type="primary" @click="printPreview"> 打印</el-button>
      <el-button type="primary" @click="handleSave"> 保存</el-button>
      <el-button @click="$router.back()"> 返回</el-button>
    </div>
    <div class="printer-designer">
      <div class="designer-meta">
        <el-card header="基础元素">
          <div class="flex flex-row flex-wrap">
            <div
              class="meta-item ep-draggable-item shadow-md"
              v-for="item in metaList"
              :key="item.tid"
              :tid="item.tid"
            >
              <div>{{ item.txt }}</div>
            </div>
          </div>
        </el-card>
        <el-card header="填充数据" class="mt-6">
          <el-input
            type="textarea"
            :rows="10"
            placeholder="请输入JSON格式的填充数据"
            v-model="printData"
          />
        </el-card>
      </div>
      <div class="designer-panel shadow" id="hiprint-printTemplate"></div>
      <div class="designer-attr shadow" id="PrintElementOptionSetting"></div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  // import { useRoute } from 'vue-router';
  import { hiprint, hiPrintPlugin, defaultElementTypeProvider } from 'vue-plugin-hiprint';
  import modal from '@/plugins/modal';

  hiPrintPlugin.disAutoConnect();

  // const route = useRoute();

  const printData = ref('{}');
  const templateObj = ref({});
  const metaList = ref([
    { txt: '文本', tid: 'defaultModule.text' },
    { txt: '图片', tid: 'defaultModule.image' },
    { txt: '长文', tid: 'defaultModule.longText' },
    { txt: '表格', tid: 'defaultModule.table' },
    // { txt: 'html', tid: 'defaultModule.html' },
    // { txt: '自定义', tid: 'defaultModule.customText' }
    { txt: '横线', tid: 'defaultModule.hline' },
    { txt: '竖线', tid: 'defaultModule.vline' },
    { txt: '矩形', tid: 'defaultModule.rect' },
    { txt: '圆形', tid: 'defaultModule.oval' },
  ]);
  const curPaper = ref('A4');
  const paperTypes = ref([
    { type: 'A3', width: 420, height: 296.6 },
    { type: 'A4', width: 210, height: 296.6 },
    { type: 'A5', width: 210, height: 147.6 },
    { type: 'B3', width: 500, height: 352.6 },
    { type: 'B4', width: 250, height: 352.6 },
    { type: 'B5', width: 250, height: 175.6 },
  ]);
  const scaleValue = ref(1);
  const scaleMax = ref(5);
  const scaleMin = ref(0.5);
  const hiprintTemplate = ref(null);

  // function checkId() {
  //   const { id } = route.query;
  //   if (!id) {
  //     modal.msgError('缺少模版ID');
  //     return false;
  //   }
  //   return getTemplate(id)
  //     .then((res) => {
  //       templateObj.value = res.data;
  //       return true;
  //     })
  //     .catch(() => {
  //       return false;
  //     });
  // }

  function initPrint() {
    hiprint.init({ providers: [defaultElementTypeProvider()] });
  }

  function buildLeftElement() {
    // eslint-disable-next-line
    hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
  }

  function buildDesigner() {
    // eslint-disable-next-line
    $('#hiprint-printTemplate').empty();
    hiprintTemplate.value = new hiprint.PrintTemplate({
      settingContainer: '#PrintElementOptionSetting',
      template: JSON.parse(templateObj.value.temContent || '{}'),
    });
    hiprintTemplate.value.design('#hiprint-printTemplate');
  }

  function printPreview() {
    const options = { leftOffset: 0, topOffset: 0 };
    try {
      const d = JSON.parse(printData.value);
      hiprintTemplate.value.print(d, options);
    } catch (e) {
      modal.msgError('填充数据格式不正确');
    }
  }

  function handlePaperChange(type) {
    const one = paperTypes.value.find((k) => k.type === type);
    if (one) {
      hiprintTemplate.value.setPaper(one.width, one.height);
    }
  }

  function rotatePaper() {
    hiprintTemplate.value.rotatePaper();
  }

  function clearPaper() {
    hiprintTemplate.value.clear();
  }

  function exportJson() {
    return hiprintTemplate.value.getJson();
  }

  function changeScale(big) {
    let _scaleValue = scaleValue.value;
    if (big) {
      _scaleValue += 0.1;
      if (_scaleValue > scaleMax.value) {
        _scaleValue = 5;
      }
    } else {
      _scaleValue -= 0.1;
      if (_scaleValue < scaleMin.value) {
        _scaleValue = 0.5;
      }
    }
    hiprintTemplate.value.zoom(_scaleValue);
    scaleValue.value = _scaleValue;
  }

  function handleSave() {
    templateObj.value.temContent = JSON.stringify(exportJson());
    // updateTemplate(templateObj.value).then(() => {
    //   modal.msgSuccess('保存成功');
    // });
  }

  initPrint();

  onMounted(async () => {
    // const ret = await checkId()
    // if (ret) {
    setTimeout(() => {
      buildLeftElement();
      buildDesigner();
    }, 1000);
    // }
  });
</script>

<style scoped lang="scss">
  .printer-designer-op {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 40px;
  }

  .printer-designer {
    position: relative;
    margin-top: 10px;

    .designer-meta {
      position: absolute;
      top: 0;
      left: 0;
      width: 350px;

      .meta-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 145px;
        height: 80px;
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 500;

        &:nth-of-type(2n + 1) {
          margin-right: 10px;
        }
      }
    }

    .designer-panel {
      position: relative;
      margin-right: 370px;
      margin-left: 370px;
      padding: 20px;
    }

    .designer-attr {
      position: absolute;
      top: 0;
      right: 0;
      width: 350px;
    }
  }
</style>
